package cn.shengchao.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import cn.shengchao.base.enums.DisEnableStatusEnum;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeContentProductThird;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeContentInfoService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeContentProductThirdService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeNodeInfoService;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.base.TransResult;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeContentRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstar.rpc.distribute.req.ProductThirdDistributeProxyIdReq;
import cn.shengchao.examstar.rpc.distribute.req.ProductThirdDistributeProxyReq;
import cn.shengchao.examstar.rpc.distribute.req.ThirdProductDistributeUserQueryPage;
import cn.shengchao.examstar.rpc.distribute.resp.ThirdProductDistributeForUserRespEntity;
import cn.shengchao.examstar.rpc.distribute.resp.ThirdProductDistributeProxyInfoRespEntity;
import cn.shengchao.examstar.rpc.product.api.IContentProductTypeRpc;
import cn.shengchao.examstar.rpc.product.base.ContentProductStruct;
import cn.shengchao.examstar.rpc.product.base.ProductTypeTree;
import cn.shengchao.examstar.rpc.product.base.SimpleProduct;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

/**
 * @program: examstarapi
 * @description: 内容产品Rpc实现
 * @author: Xiong weiqiang
 * @create: 2025-06-10 17:21
 */
@DubboService
public class ContentProductTypeRpc implements IContentProductTypeRpc {
    @Autowired
    private DistributeContentProductThirdService distributeContentProductThirdService;
    @Autowired
    private DistributeContentInfoService distributeContentInfoService;
    @Autowired
    private DistributeNodeInfoService distributeNodeInfoService;
    @Override
    public List<ProductTypeTree> getContentProductTypes() {
        return ContentProductStruct.getProductTypeTrees();
    }
    @Override
    public List<SimpleProduct> listProductDetails () {
        List<SimpleProduct> products=new ArrayList<>();
        SimpleProduct  product= SimpleProduct.builder().productType("COURSE").productName("课程").productId(0L).build();
        products.add(product);
        products.addAll(Objects.requireNonNull(ContentProductStruct.getSimpleProductList(List.of("PRODUCT_THIRD_YCBDC", "PRODUCT_THIRD_CAP"))));
        return products;
    }


    @Override
    public PageResult<ThirdProductDistributeForUserRespEntity> getThirdProductDistributeListForUser(ThirdProductDistributeUserQueryPage thirdProductDistributeUserQueryPage) {
        return distributeContentProductThirdService.pageList(thirdProductDistributeUserQueryPage);
    }

    @Override
    public TransResult<String> addThirdProductDistributeProxyForUser(ProductThirdDistributeProxyReq req) {
        BigDecimal percent=distributeContentProductThirdService.sumPercentUseExcludeUserId(req.getProductId(),req.getUserId());
        BigDecimal thisPercent=percent.add(req.getProxyPercent());
        if (thisPercent.doubleValue()>50){
            return TransResult.fail("配置第三方会员产品时错误：产品分销比例超过50%");
        }
        SimpleProduct distributeContentDto = ContentProductStruct.getSimpleProductById(req.getProductId());
        if (distributeContentDto == null){
            return TransResult.fail("配置第三方会员产品时错误：产品不存在");
        }
        if (req.getUserId()==0L){
            return TransResult.fail("配置第三方会员产品时错误：平台不需要设置代理");
        }
        DistributeNodeInfo distributeNodeInfo=distributeNodeInfoService.getNodeInfoForUser(req.getUserId(), DistributeTypeEnum.TYPE_CTPD);
        if (distributeNodeInfo==null){
            return TransResult.fail("配置第三方会员产品时错误：用户非内容供应商");
        }

        if (Arrays.asList("PRODUCT_THIRD_YCBDC","PRODUCT_THIRD_CAP").contains(distributeContentDto.getProductType())){
            DistributeContentProductThird distributeContentProductThird = new DistributeContentProductThird();
            distributeContentProductThird.setUserId(req.getUserId());
            distributeContentProductThird.setProductId(req.getProductId());
            distributeContentProductThird.setProductType(distributeContentDto.getProductType());
            distributeContentProductThird.setProductName(distributeContentDto.getProductName());
            if (distributeContentProductThird.getValidStartTime()==null||distributeContentProductThird.getValidStartTime().getTime()<=new Date().getTime()){
                distributeContentProductThird.setValidStartTime(new Date());
            }
            distributeContentProductThird.setValidStartTime(req.getValidStartTime());
            distributeContentProductThird.setValidEndTime(req.getValidEndTime());
            distributeContentProductThird.setEnableStatus(DisEnableStatusEnum.ENABLE.getValue());
            distributeContentProductThird.setDataStatus(DistributeDataStatusEnum.STATUS_CURT.getStatus());
            distributeContentProductThird.setStablePercent(req.getProxyPercent());
            if (distributeNodeInfo.getDistributeRoleCode().equals(DistributeContentRoleEnum.ROLE_CTPD_EMP.getCode())){
                distributeContentProductThird.setContentDistributeUserId(distributeNodeInfo.getAdminUserId());
            }else {
                distributeContentProductThird.setContentDistributeUserId(req.getUserId());
            }
            distributeContentProductThirdService.saveUserNewSetting(distributeContentProductThird);
            return TransResult.success("配置成功");
        }else{
            return TransResult.fail("配置第三方会员产品时错误：产品类型错误");
        }
    }

    @Override
    public TransResult<String> deleteThirdProductDistributeProxyForUser(ProductThirdDistributeProxyIdReq req) {
        List<DistributeContentProductThird> distributeContentProductThirds =distributeContentProductThirdService.list(Wrappers.lambdaQuery(DistributeContentProductThird.class)
                .eq(DistributeContentProductThird::getUserId,req.getUserId())
                .eq(DistributeContentProductThird::getProductId,req.getProductId()).eq(DistributeContentProductThird::getDataStatus,1)
        );
        if (CollUtil.isNotEmpty(distributeContentProductThirds)){
            for (DistributeContentProductThird distributeContentProductThird: distributeContentProductThirds){
                distributeContentProductThird.setValidEndTime(new Date());
                distributeContentProductThird.setDataStatus(DistributeDataStatusEnum.STATUS_HIS.getStatus());
                distributeContentProductThirdService.updateById(distributeContentProductThird);
            }
        }
        return TransResult.success("删除成功");
    }

    @Override
    public List<SimpleProduct> listThirdMemberProductExcludeUser(Long userId) {
        List<SimpleProduct> products=ContentProductStruct.getSimpleProductList(List.of("PRODUCT_THIRD_YCBDC","PRODUCT_THIRD_CAP"));
        for (SimpleProduct product: products){
            BigDecimal percent=distributeContentProductThirdService.sumPercentUseExcludeUserId(product.getProductId(),userId);
            product.setAvailPercent(BigDecimal.valueOf(50).subtract(percent));
        }
        return products;
    }

    @Override
    public List<ThirdProductDistributeProxyInfoRespEntity> selectListByProductId(Long productId) {
        return distributeContentProductThirdService.selectListByProductId(productId);
    }

    @Override
    public ThirdProductDistributeForUserRespEntity loadThirdMemberProxy(Long userId, Long productId) {
        List<DistributeContentProductThird> distributeContentProductThirds =distributeContentProductThirdService.list(Wrappers.lambdaQuery(DistributeContentProductThird.class)
                .eq(DistributeContentProductThird::getProductId,  productId)
                .eq(DistributeContentProductThird::getUserId, userId)
                .eq(DistributeContentProductThird::getDataStatus, 1)
                .eq(DistributeContentProductThird::getEnableStatus, 1)
        );
        if (CollUtil.isNotEmpty(distributeContentProductThirds)){
            ThirdProductDistributeForUserRespEntity  thirdProductDistributeForUserRespEntity=new ThirdProductDistributeForUserRespEntity();
            thirdProductDistributeForUserRespEntity.setProductId(distributeContentProductThirds.getFirst().getProductId());
            thirdProductDistributeForUserRespEntity.setProductType(distributeContentProductThirds.getFirst().getProductType());
            thirdProductDistributeForUserRespEntity.setProductName(distributeContentProductThirds.getFirst().getProductName());
            thirdProductDistributeForUserRespEntity.setUserId(distributeContentProductThirds.getFirst().getContentDistributeUserId());
            thirdProductDistributeForUserRespEntity.setStablePercent(distributeContentProductThirds.getFirst().getStablePercent());
            thirdProductDistributeForUserRespEntity.setValidStartTime(distributeContentProductThirds.getFirst().getValidStartTime());
            thirdProductDistributeForUserRespEntity.setValidEndTime(distributeContentProductThirds.getFirst().getValidEndTime());
            return thirdProductDistributeForUserRespEntity;
        }else {
            return new ThirdProductDistributeForUserRespEntity();
        }
    }
}